package com.summer.safe.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.summer.safe.base.BaseController;
import com.summer.safe.base.Page;
import com.summer.safe.config.annotation.ResultWrapper;
import com.summer.safe.config.result.*;
import com.summer.safe.entity.GenScheme;
import com.summer.safe.entity.GenTable;
import com.summer.safe.entity.GenTableColumn;
import com.summer.safe.service.GenSchemeService;
import com.summer.safe.system.service.DictService;
import com.summer.safe.service.GenTableService;
import com.summer.safe.utils.StringUtils;
import com.summer.safe.utils.ToolUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成业务
 */
@Controller
@RequestMapping(value = "/gen/genTable")
public class GenTableController extends BaseController {

    @Autowired
    private GenTableService tableService;
    @Autowired
    private GenSchemeService schemeService;

    @Autowired
    public DictService dictService;

    @Autowired
    private Environment environment;

    /**
     * 跳转到业务表的列表
     * @return
     */
    @RequiresPermissions("gen:genTable:view")
    @GetMapping
    public String index(Model model) {
        Map<String, String> map = new HashMap<>();
        tableService.getFindTableList(new GenTable()).forEach(g ->

                map.put(g.getName(), g.getName() + ":" + g.getComments())
        );
        model.addAttribute("table", map);
        return "list.html";
    }

    /**
     * 获得业务表数据
     * @param genTable
     * @param request
     * @return
     */
    @RequestMapping("/dataList")
    @ResultWrapper
    public Page list(GenTable genTable, HttpServletRequest request) {
        Page<GenTable> page = tableService.findPage(new Page(request), genTable);
        return page;
    }

    /**
     * 增加数据信息
     * @param genTable
     * @param model
     * @return
     */

    @RequestMapping("/add")
    public String add(GenTable genTable, Model model) {
        GenScheme genScheme=new GenScheme();
        Map<String, String> map = new HashMap<>();
        tableService.getFindTableList(genTable).forEach(g ->
            map.put(g.getName(), g.getName() + ":" + g.getComments())
        );
        if(StringUtils.isBlank(genTable.getId())){
            genScheme.setPackageName(ToolUtil.getConfigName("mybatis.typeAliasesPackage"));
        }else {
            genScheme=schemeService.getTableId(genTable.getId());
        }

        model.addAttribute("table", map);
        model.addAttribute("genTable", genTable);
        model.addAttribute("genScheme", genScheme);
        return "add.html";
    }


    @GetMapping("/getTable")
    @ResultWrapper(ResultCode.SUCCESS_QUERY)
    public GenTable table(GenTable genTable) {
        String tableId = genTable.getId();
        if (StringUtils.isEmpty(tableId)) {
            List<GenTable> genTables = tableService.findTableList(genTable);
            if (genTables.size() > 0) {
                genTable = genTables.get(0);
                genTable.setClassName(ToolUtil.intercept(genTable.getName()));
                genTable.setId(tableId);
            }
        } else {
            genTable = tableService.get(tableId);
        }
        return genTable;
    }

    @RequestMapping("/tableColumnList")
    @ResultWrapper
    public List<GenTableColumn> tableColumnList(GenTable genTable) {
        List<GenTableColumn> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(genTable.getId())) {
            GenTableColumn tableColumn = new GenTableColumn();
            tableColumn.setGenTable(genTable);
            list = tableService.findTableColumnList(tableColumn);
        }
        if (list.size() == 0 || StringUtils.isEmpty(genTable.getId())) {
            list = tableService.findTableColumnList(genTable);
        }
        return list;
    }

    @PostMapping(value = "/save")
    @ResultWrapper(ResultCode.SUCCESS_SAVE)
    public void save(@RequestBody String param) {

        JSONObject o = JSON.parseObject(param);
        //保存表
        JSONObject tableObj = (JSONObject) o.get("table");
        GenTable table = JSON.parseObject(tableObj.toJSONString(), GenTable.class);
        List<GenTable> genTables = tableService.findList(table);
        if (genTables.size() > 0) {
            table.setId(genTables.get(0).getId());
        }
        tableService.save(table);

        //删除旧列(物理删除)
        tableService.deleteByGenTableId(table.getId());
            //新表列
        JSONArray tableColumnArray = (JSONArray) o.get("listColumn");
        List<GenTableColumn> tableColumnList = JSON.parseArray(tableColumnArray.toJSONString(), GenTableColumn.class);
        tableColumnList.forEach(tableColumn -> {
            tableColumn.setGenTable(table);
            tableService.save(tableColumn);

        });
        }


    @RequestMapping(value = "delete")
    @ResultWrapper(ResultCode.SUCCESS_DELETE)
    public void save(GenTable genTable) {
        tableService.delete(genTable);
    }


}
